<?php
namespace app\common\controller;

use app\api\consDir\ErrorConst;
use app\api\provider\Userinfo;
use app\BaseController;
use app\common\utils\CommonUtil;
use think\App;
use think\Response;

class AgencyController extends BaseController
{
    //不需要登录节点
    protected $noNeedLogin = ['*'];

    //参数
    public $param = [];

    /**
     * RestController constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        if ( ! Userinfo::getInstance()->match($this->noNeedLogin, $this->request) && ! $this->app->userinfo->id) {
            CommonUtil::throwException(
                ErrorConst::NOT_LOGIN_ERROR,
                ErrorConst::NOT_LOGIN_ERROR_MSG
            );
        }
        $role = $this->app->userinfo->role ?? '';
        // var_dump($this->app->userinfo);exit;
        // var_dump($role);exit;
        if ($role != 'agency') {
            CommonUtil::throwException(
                ErrorConst::NOT_LOGIN_ERROR,
                ErrorConst::NOT_LOGIN_ERROR_MSG
            );
        }
        $this->param = input();
    }

    /**
     * @param $param
     */
    public function checkParam($param)
    {
        foreach ($param as $k => $v) {
            if ( ! isset($this->param[$v])) {
                $this->result(ErrorConst::BASE_ERROR);
            }
        }
    }

    /**
     * 返回
     * @param null $data
     */
    public function result($data = null)
    {
        is_object($data) && $data = objectToArray($data);
        $code                     = $data['code'] ?? ErrorConst::SUCCESS_CODE;
        $msg                      = $data['msg'] ?? ErrorConst::SUCCESS_CODE_MSG;
        $rData                    = empty($data) ? new \stdClass() : (is_object($data) ? $data->toArray() : $data);
        if ( ! is_array($data) && ! is_object($data)) {
            $rData = new \stdClass();
            if (is_numeric($data)) {
                $code = $data;
            } elseif ($data !== true) {
                $code  = ErrorConst::BASE_ERROR;
                $msg   = $data;
                $rData = new \stdClass();
            } elseif ($data == true) {
                $rData = new \stdClass();
            }
        }
        CommonUtil::response($code, $msg, $rData);
        return true;
    }
}
